package com.daxia.bumall.web.controller.admin;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.daxia.bumall.basemodel.CoreUser;
import com.daxia.bumall.common.AuditStatus;
import com.daxia.bumall.common.CompanyStatus;
import com.daxia.bumall.common.FactoryCode;
import com.daxia.bumall.common.FactoryInfoStatus;
import com.daxia.bumall.common.Logs;
import com.daxia.bumall.common.RoleCode;
import com.daxia.bumall.common.SeedStatus;
import com.daxia.bumall.common.SmsSendType;
import com.daxia.bumall.common.TaskStatus;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.CompanyDTO;
import com.daxia.bumall.dto.DesignerDTO;
import com.daxia.bumall.dto.FactoryInfoDTO;
import com.daxia.bumall.dto.JsonResultDTO;
import com.daxia.bumall.dto.PayDTO;
import com.daxia.bumall.dto.RoleDTO;
import com.daxia.bumall.dto.TaskDTO;
import com.daxia.bumall.dto.UserDTO;
import com.daxia.bumall.dto.UserTaskDTO;
import com.daxia.bumall.model.City;
import com.daxia.bumall.model.Department;
import com.daxia.bumall.model.District;
import com.daxia.bumall.model.Province;
import com.daxia.bumall.model.Role;
import com.daxia.bumall.model.Task;
import com.daxia.bumall.model.User;
import com.daxia.bumall.model.UserRole;
import com.daxia.bumall.service.DesignerService;
import com.daxia.bumall.service.FactoryInfoService;
import com.daxia.bumall.service.RoleService;
import com.daxia.bumall.service.TaskService;
import com.daxia.bumall.service.UserRoleService;
import com.daxia.bumall.service.UserService;
import com.daxia.bumall.service.UserTaskService;
import com.daxia.bumall.support.Page;
import com.daxia.bumall.util.BeanMapper;
import com.daxia.bumall.util.SmsService;
import com.daxia.bumall.util.SpringSecurityUtils;
import com.daxia.bumall.web.controller.BaseController;

@Controller
@RequestMapping(value = "/admin/user", produces="text/html;charset=UTF-8")
public class AdminUserController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private FactoryInfoService factoryInfoService;
	@Autowired
	private DesignerService designerService;
	@Autowired
	private UserTaskService userTaskService;
    @Autowired
    private TaskService taskService;
	
	
	@RequestMapping(value = "/auditSubAccount")
	public String auditSubAccount(PayDTO dto, Map<String, Object> map, Page page) {
		dto.setIsSuccess(true);
		List<PayDTO> dtos = payService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/user/user_audit_list";
	}

	
	@RequestMapping(value = "/newSubAccount")
	public String newSubAccount(String startIndex, Map<String, Object> map) {
		if (UserType.DecorateCompany.getValue() == getCurrentUserDTO().getType()) {
			// 如果是装修公司，就跳到别外的页面
			//List<DesignerDTO> designers = designerService.findByCompanyUserId(getCurrentUserDTO().getId());
			return "redirect:/admin/user/designerList";
		}
		map.put("startIndex", StringUtils.isNotBlank(startIndex) ? startIndex : "0");
		map.put("provinces", provinceService.findAll());
		return "admin/user/user_sub_add";
	}

	/**
	 * 子帐号列表
	 * @param dto
	 * @param map
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/mySubAccounts")
	public String mySubAccounts(UserDTO dto, Map<String, Object> map, Page page) {
		if (UserType.DecorateCompany.getValue() == getCurrentUserDTO().getType()) {
			// 如果是装修公司，就跳到别外的页面
			//List<DesignerDTO> designers = designerService.findByCompanyUserId(getCurrentUserDTO().getId());
			return "redirect:/admin/user/designerList";
		}
		return "admin/user/user_sub_tab";
	}
	
	@RequestMapping(value = "userAuditDetail")
	public String userAuditDetail(DesignerDTO dto, Map<String, Object> map) {
		
		return "admin/user_audit_detail";
	}
	
	/**
	 * 
	 * @param id companyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("companyAudit")
	public String companyAudit(Long id, Map<String, Object> map) throws Exception {
		map.put("n", companyService.load(id));
		return "admin/user/user_companyAudit";
	}
	
	@Transactional
	@ResponseBody
	@RequestMapping("auditCompanySave")
	public String auditCompanySave(Long companyId, Integer auditStatus, String auditRemark, JsonResultDTO resultDTO) throws Exception {
		assertTrue(StringUtils.isNotBlank(auditRemark), "请填写备注");
		CompanyDTO old = companyService.load(companyId);
		if (old.getAuditStatus() == null) {
			old.setAuditStatus(AuditStatus.NotAudit.getValue());
		}
		if (old.getAuditStatus() != AuditStatus.Success.getValue() && auditStatus == AuditStatus.Success.getValue()) {
			// 审核通过
			dispatcherService.onCompanyActivated(old.getUser().getId());
		}
		old.setAuditStatus(auditStatus);
		old.setAuditUser(getCurrentUserDTO());
		old.setAuditRemark(auditRemark);
		old.setAuditTime(new Date());
		
		companyService.updateAllFields(old);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobile", old.getUser().getMobile());
		SmsService.sendWithTemplate(old.getUser().getMobile(), SmsSendType.CompanyAuditedBackend.getValue(), params);
		return okAndClose(resultDTO);
	}
	
	/**
	 * 只有城市运营商会调这个
	 * @param type
	 * @param startIndex
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/newSubAccountDetail")
	public String newSubAccountDetail(String type, String startIndex, Map<String, Object> map) {
		map.put("provinces", provinceService.findAll());
		map.put("startIndex", StringUtils.isNotBlank(startIndex) ? startIndex : "0");
		map.put("province", getCurrentUserDTO().getProvince());
		map.put("city", getCurrentUserDTO().getCity());
		if (getCurrentUserDTO().getCity() != null) {
			//map.put("districts", districtService.findByCity(getCurrentUserDTO().getCity().getId()));
			// 查出该城市运营商所在城市的所有装修公司
			List<CompanyDTO> companyList = companyService.findByCity(getCurrentUserDTO().getCity().getId());
			map.put("companyList", companyList);
		}
		
		return "admin/user/user_sub_" + type;
	}
	
	@RequestMapping(value = "/seedUser")
	public String seedUser(UserDTO dto, Map<String, Object> map, Page page) {
		dto.setSeedUser(true);
		List<UserDTO> dtos = userService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/user/user_seed";
	}
	
	@RequestMapping(value = "/auditSeedUser")
	public String auditSeedUser(Long id, Map<String, Object> map) {
		UserDTO dto = userService.load(id);
		map.put("n", dto);
		return "admin/user/user_seed_audit";
	}
	
	@RequestMapping(value = "/auditSeedUserSave")
	@ResponseBody
	public String auditSeedUserSave(UserDTO dto, JsonResultDTO resultDTO) {
		userService.updateSeedStatus(dto);
		if (dto.getSeedStatus().intValue() == SeedStatus.attend.getValue()) {
			TaskDTO taskQuery = new TaskDTO();
			taskQuery.setStatus(TaskStatus.Active.getValue());
			List<TaskDTO> tasks = taskService.find(taskQuery, null);
			for (TaskDTO taskDTO : tasks) {
				UserTaskDTO userTaskDTO = new UserTaskDTO();
				userTaskDTO.setQuota(taskDTO.getQuota());
				Task task = new Task();
				task.setId(taskDTO.getId());
				userTaskDTO.setTask(task);
				User user = new User();
				user.setId(dto.getId());
				userTaskDTO.setUser(user);
				userTaskService.create(userTaskDTO );
			}
		}
		return okAndClose(resultDTO);
	}

	@RequestMapping(value = "/detail")
	public String detail(Integer type, Long parentId, Map<String, Object> map, Long id, boolean seedUser) {
		if (id != null) {
			UserDTO dto = userService.load(id);
			map.put("n", dto);
		}
		map.put("seedUser", seedUser);
		map.put("provinces", provinceService.findAll());
		map.put("type", type);
		map.put("parentId", parentId);
		map.put("departments", departmentService.findAll());
		return "admin/user/user_detail";
	}

	@Transactional
	@ResponseBody
	@RequestMapping(value = "/save")
	public String save(UserDTO dto, Integer type, JsonResultDTO resultDTO) throws Exception {
		Logs.COMMON.debug("type: " + type);
		if (dto.getDistrict() != null && dto.getDistrict().getId() == null) {
			dto.setDistrict(null);
		}
		if (dto.getParent() != null && dto.getParent().getId() == null) {
			dto.setParent(null);
		}
		if (dto.getId() == null) {
			Long id = userService.create(dto);
			Logs.COMMON.debug("dto.getType: " + dto.getType());
			if (dto.getType() == UserType.Designer.getValue()) {
				User user = new User();
				user.setId(id);
				DesignerDTO designerDTO = new DesignerDTO();
				designerDTO.setUser(user);
				designerDTO.setProvince(dto.getProvince());
				designerDTO.setCity(dto.getCity());
				designerDTO.setDistrict(user.getDistrict());
				designerService.create(designerDTO);
			} else if (dto.getType() == UserType.DecorateCompany.getValue()){
				throw new RuntimeException("不允许在此处新增装修公司");
			}
		} else {
			UserDTO old = userService.load(dto.getId());
			old.setMobile(dto.getMobile());
			old.setSex(dto.getSex());
			if (dto.getProvince() != null && dto.getProvince().getId() != null) {
				old.setProvince(dto.getProvince());
			}
			if (dto.getCity() != null && dto.getCity().getId() != null) {
				old.setCity(dto.getCity());
			}
			if (dto.getDistrict() != null && dto.getDistrict().getId() != null) {
				old.setDistrict(dto.getDistrict());
			}
			old.setHeadImage(dto.getHeadImage());
			old.setAddress(dto.getAddress());
			old.setNickName(dto.getNickName());
			old.setRealName(dto.getRealName());
			old.setBirthday(dto.getBirthday());
			old.setType(dto.getType());
			userService.updateAllFields(old);
		}
		return okAndClose(resultDTO);
	}

    
	@ResponseBody
	@RequestMapping(value = "/delete") 
	public String delete(Long[] ids, JsonResultDTO resultDTO) throws IOException {
		userService.deleteByIds(ids);
		return okAndRefresh(resultDTO);
	}
	
	@RequestMapping(value = "/list")
	public String list(Boolean onlyQuery, Integer fromType, Integer type, UserDTO dto, Map<String, Object> map, Page page) {
		map.put("onlyQuery", onlyQuery);
		if (fromType != null && fromType == UserType.City.getValue()) {
			dto.setParent(new User());
			dto.getParent().setId(SpringSecurityUtils.getCurrentUser().getId());
			map.put("parentId", SpringSecurityUtils.getCurrentUser().getId());
		}
		List<UserDTO> dtos = userService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		map.put("type", type);
		map.put("fromType", fromType);
		map.put("user", getCurrentUserDTO());
		map.put("provinces", provinceService.findAll());
		map.put("departments", departmentService.findAll());
		return "admin/user/user_list";
	}
	
	@RequestMapping(value = "/auth")
	public String auth(Map<String, Object> map, Long userId, RoleDTO dto, Page page) {
		if (userId != null) {
			List<Role> roles = userRoleService.findRolesByUserId(userId);
			List<RoleDTO> list = roleService.list(dto, page);
			for (RoleDTO model : list) {
				for (Role role : roles) {
					if (role.getId() == model.getId()) {
						model.setChecked(true);
					}
				}
			}
			map.put("userId", userId);
			map.put("list", list);
			map.put("query", dto);
		}
		return "admin/user/user_auth";
	}
	
	@RequestMapping(value = "/authSave")
	@ResponseBody
	public String authSave(Long[] ids, Long userId, JsonResultDTO resultDTO) {
		userRoleService.save(ids, userId);
		return okAndRefresh(resultDTO);
	}
	
	@RequestMapping(value = "/reset")
	public String reset(Map<String, Object> map, Long userId) {
		if (userId != null) {
			UserDTO dto = userService.load(userId);
			map.put("n", dto);
		}
		return "admin/user/user_reset";
	}
	/**
	 * 
	 * @param map
	 * @param userId 其实是companyId
	 * @return
	 */
	@RequestMapping(value = "/resetByCompany")
	public String resetByCompany(Map<String, Object> map, Long userId) {
		if (userId != null) {
			map.put("n", companyService.load(userId).getUser());
		}
		return "admin/user/user_reset";
	}
	
	@RequestMapping(value = "/reset2")
	public String reset2(Map<String, Object> map) {
		UserDTO dto = userService.load(getCurrentUserDTO().getId());
		map.put("n", dto);
		return "admin/user/user_reset2";
	}
	
	@RequestMapping(value = "/setPrice")
	public String setPrice(Map<String, Object> map, Long userId) {
		if (userId != null) {
			UserDTO dto = userService.load(userId);
			map.put("n", dto);
		}
		return "admin/user/user_setPrice";
	}
	
	@ResponseBody
	@RequestMapping(value = "/resetPassword") 
	public String resetPassword(String newPassword, String repeatPassword, Long userId) {
		assertTrue(StringUtils.isNotBlank(newPassword), "密码不能为空");
		assertTrue(newPassword.equals(repeatPassword), "两次密码输入不一致");
		userService.resetPassword(newPassword, userId);
		return ok();
	}
	@ResponseBody
	@RequestMapping(value = "/savePrice") 
	public String savePrice(String priceFactor, Long userId) {
		UserDTO user = userService.load(userId);
		try {
			Double d = Double.parseDouble(priceFactor);
			user.setPriceFactor(d);
			userService.updateAllFields(user);
		} catch (Exception e) {
			throw new RuntimeException("格式错误");
		}
		return okAndRefresh(new JsonResultDTO());
	}
	
	@ResponseBody
	@RequestMapping(value = "/companySave") 
	public String companySave(CompanyDTO companyDTO, JsonResultDTO resultDTO) {
		CompanyDTO company = userService.companySave(companyDTO);
		/**
		 * 解决json parse异常  进入user死循环
		 */
		company.getUser().setRecUser(null);
		company.getUser().setParent(null);
		return toJson(company);
	}
	
	/**
	 * 只有城市运营商会调用这个方法
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "/designerSave") 
	public String designerSave(String mobile, String realName, Integer sex, Integer age, Integer workAge, Long companyId, String remark) throws Exception {
		assertTrue(StringUtils.isNotBlank(mobile), "请输入手机号码");
		UserDTO user = userService.findByUsername(mobile);
		assertTrue(user == null, "该手机号码已经被注册了!");
		
		assertTrue(StringUtils.isNotBlank(realName), "请输入真实姓名");
		assertTrue(workAge != null, "请输入从业年限");
		
		// 创建对应的用户
		user = new UserDTO();
		user.setUsername(mobile);
		user.setRealName(realName);
		//user.setNickName(realName);
		user.setMobile(mobile);
		user.setPassword(passwordEncoder.encodePassword("123456", mobile));
		user.setCreatetime(new Date());
    	user.setType(UserType.Designer.getValue());
    	user.setSex(sex);
    	
		DesignerDTO d = new DesignerDTO();
		
		d.setCreator(getCurrentUserDTO());
		d.setDealCount(0);
		d.setFanCount(0);
		d.setMobile(mobile);
		d.setRecommend(0);
		
		d.setUser(user);
		d.setWorkAge(workAge);
		
			d.setRemark(remark);
			
			d.setAuditRemark("城市运营商创建自动审核");
			d.setAuditStatus(AuditStatus.Success.getValue());
			d.setAuditTime(new Date());
			d.setAuditUser(getCurrentUserDTO());
			
		if (companyId != null) {
			CompanyDTO c = companyService.load(companyId);
			d.setCompany(c.getName());
			d.setCompanyUser(c);
			
			Province p = c.getProvince() == null ? c.getUser().getProvince() : c.getProvince();
			user.setProvince(p);
			d.setProvince(p);
			
			City city = c.getCity() == null ? c.getUser().getCity() : c.getCity();
			user.setCity(city);
			d.setCity(city);
			
			District district = c.getDistrict() == null ? c.getUser().getDistrict() : c.getDistrict();
			user.setDistrict(district);
			d.setDistrict(district);
		}
		Long userId = userService.create(user);
		d.setUser(userService.load(userId));
		
		userRoleService.addRole(RoleCode.Designer, userId);
		
		designerService.create(d);
		
		SmsService.sendWithTemplate(mobile, SmsSendType.DesignerAudited.getValue(), new HashMap<String, Object>());
		
		return ok("创建成功，初始登陆密码为123456");
	}
	
	/**
	 * 保存设计师。省市区只能和装修公司一致，不允许自己修改
	 * @param mobile
	 * @param password
	 * @param realName
	 * @param companyId
	 * @return
	 * @throws Exception 
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "/designerSaveNew") 
	public String designerSaveNew(
			String mobile,
			String realName,
			Long companyId,
			Integer workAge,
			String serviceArea,
			String goodAtStyles,
			Integer recommend,
			String description,
			String headImage,
			Integer sex
			) throws Exception {
		assertTrue(StringUtils.isNotBlank(mobile), "请输入手机号码");
		UserDTO user = userService.findByUsername(mobile);
		assertTrue(user == null, "该手机号码已经被注册了!");
		
		assertTrue(StringUtils.isNotBlank(realName), "请输入真实姓名");
		assertTrue(workAge != null, "请输入从业年限");
		assertTrue(StringUtils.isNotBlank(serviceArea), "请输入服务范围");
		assertTrue(StringUtils.isNotBlank(goodAtStyles), "请输入擅长风格");
		
		// 创建对应的用户
		user = new UserDTO();
		user.setUsername(mobile);
		user.setRealName(realName);
		//user.setNickName(realName);
		user.setMobile(mobile);
		user.setPassword(passwordEncoder.encodePassword("123456", mobile));
		user.setCreatetime(new Date());
    	user.setType(UserType.Designer.getValue());
    	user.setHeadImage(headImage);
    	user.setSex(sex);
    	
		DesignerDTO d = new DesignerDTO();
		
		d.setCreator(getCurrentUserDTO());
		d.setDealCount(0);
		d.setDescription(description);
		d.setFanCount(0);
		d.setGoodAtStyles(goodAtStyles);
		d.setMobile(mobile);
		d.setRecommend(recommend);
		
		d.setServiceArea(serviceArea);
		d.setUser(user);
		d.setWorkAge(workAge);
		
		boolean isCompany = getCurrentUserDTO().getType() == UserType.DecorateCompany.getValue();
		if (isCompany) {
			companyId = companyService.findCompanyByUserId(getCurrentUserDTO().getId()).getId();
			d.setRemark("装修公司创建");
			d.setAuditRemark("装修公司创建自动审核");
			d.setAuditStatus(AuditStatus.Success.getValue());
			d.setAuditTime(new Date());
			d.setAuditUser(getCurrentUserDTO());
		} else {
			d.setRemark("管理人员创建");
		}
		if (companyId != null) {
			CompanyDTO c = companyService.load(companyId);
			d.setCompany(c.getName());
			d.setCompanyUser(c);
			
			Province p = c.getProvince() == null ? c.getUser().getProvince() : c.getProvince();
			user.setProvince(p);
			d.setProvince(p);
			
			City city = c.getCity() == null ? c.getUser().getCity() : c.getCity();
			user.setCity(city);
			d.setCity(city);
			
			District district = c.getDistrict() == null ? c.getUser().getDistrict() : c.getDistrict();
			user.setDistrict(district);
			d.setDistrict(district);
		}
		Long userId = userService.create(user);
		d.setUser(userService.load(userId));
		
		userRoleService.addRole(RoleCode.Designer, userId);
		
		designerService.create(d);
		
		if (isCompany) {
			SmsService.sendWithTemplate(mobile, SmsSendType.DesignerAudited.getValue(), new HashMap<String, Object>());
		}
		
		return ok("创建成功，初始登陆密码为123456");
	}
	
	/**
	 * 保存设计师 
	 * @param mobile
	 * @param password
	 * @param realName
	 * @return
	 * @throws Exception 
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "/designerSaveEdit") 
	public String designerSaveEdit(
			Long id,
			Integer workAge,
			String serviceArea,
			String goodAtStyles,
			Integer recommend,
			String description,
			String headImage,
			Integer sex
			) throws Exception {
		assertTrue(workAge != null, "请输入从业年限");
		assertTrue(StringUtils.isNotBlank(serviceArea), "请输入服务范围");
		assertTrue(StringUtils.isNotBlank(goodAtStyles), "请输入擅长风格");
		
		DesignerDTO d = designerService.load(id);
		d.setWorkAge(workAge);
		d.setGoodAtStyles(goodAtStyles);
		d.setDescription(description);
		boolean isCompany = getCurrentUserDTO().getType() == UserType.DecorateCompany.getValue();
		if (isCompany) {
			
		} else {
			if (recommend == null) {
				recommend = 0;
			}
			d.setRecommend(recommend);
		}
		designerService.updateAllFields(d);
		
		UserDTO user = userService.load(d.getUser().getId());
		user.setHeadImage(headImage);
		user.setSex(sex);
		userService.updateAllFields(user);
		
		return ok();
	}
	
	@RequestMapping(value = "/factoryList")
	public String factoryList(FactoryInfoDTO dto, Map<String, Object> map, Page page) {
		List<FactoryInfoDTO> dtos = factoryInfoService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/user/user_factoryList";
	}
	
	@RequestMapping(value = "/factorySelect")
	public String factorySelect(FactoryInfoDTO dto, Map<String, Object> map, Page page) {
		List<FactoryInfoDTO> dtos = factoryInfoService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/user/user_factorySelect";
	}
	
	@RequestMapping(value = "/factoryDetail")
	public String factoryDetail(Map<String, Object> map, Long id) {
		if (id != null) {
			FactoryInfoDTO dto = factoryInfoService.findFactoryByUserId(id);
			map.put("n", dto);
		}
		map.put("provinces", provinceService.findAll());
		return "admin/user/user_factoryDetail";
	}
	
	@Transactional
	@RequestMapping(value = "/factorySave")
	@ResponseBody
	public String factorySave(FactoryInfoDTO dto, JsonResultDTO resultDTO) {
		assertTrue(StringUtils.isNotBlank(dto.getUser().getSeq()), "供应商对应码不能为空");
		if (dto.getUser().getDistrict() != null && dto.getUser().getDistrict().getId() == null) {
			dto.getUser().setDistrict(null);
		}
		if (dto.getId() == null) {
				UserDTO userDto = BeanMapper.map(dto.getUser(), UserDTO.class); 
				userDto.setPassword(passwordEncoder.encodePassword(userDto.getPassword(), userDto.getUsername()));
				userDto.setType(UserType.Factory.getValue());
				userDto.setQQ(dto.getUser().getQQ());
				Long userId = userService.create(userDto);
				 
				userDto.setId(userId);
				dto.setUser(userDto);
				dto.setStatus(FactoryInfoStatus.Add.getValue());
				factoryInfoService.create(dto);
				
				RoleDTO roleDTO = new RoleDTO();
				roleDTO.setCode(FactoryCode.Factory.getValue());
				roleDTO = roleService.findOne(roleDTO);
				
				userRoleService.save(new Long[]{roleDTO.getId()}, userId);
		} else {
			UserDTO oldUser = userService.load(dto.getUser().getId());
			oldUser.setProvince(dto.getUser().getProvince());
			oldUser.setCity(dto.getUser().getCity());
			oldUser.setDistrict(dto.getUser().getDistrict());
			oldUser.setContactName(dto.getUser().getContactName());
			oldUser.setMobile(dto.getUser().getMobile());
			oldUser.setSeq(dto.getUser().getSeq());
			oldUser.setQQ(dto.getUser().getQQ());
			userService.updateAllFields(oldUser);
			
			FactoryInfoDTO oldFactory = factoryInfoService.load(dto.getId());
			oldFactory.setCompanyName(dto.getCompanyName());
			oldFactory.setCompanySize(dto.getCompanySize());
			oldFactory.setLiveurl(dto.getLiveurl());
			oldFactory.setVideourl(dto.getVideourl());
			
			factoryInfoService.updateAllFields(oldFactory);
		}
		return okAndClose(resultDTO);
	}
	
	@RequestMapping(value = "/myRecUsers")
	public String myRecUsers( UserDTO dto, Map<String, Object> map, Page page) {
		CoreUser currentUser = SpringSecurityUtils.getCurrentUser();
		User user = new User();
		user.setId(currentUser.getId());
		dto.setRecUser(user);
		List<UserDTO> dtos = userService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/user/user_myRecUsers";
	}
	
	@RequestMapping(value = "/designerList")
	public String designerList(DesignerDTO dto, Map<String, Object> map, Page page) {
		UserDTO user=getCurrentUserDTO();
		Integer type=user.getType();
		if(type==UserType.DecorateCompany.getValue()){//如果是装修公司
			CompanyDTO company=companyService.findCompanyByUserId(user.getId());
			dto.setCompanyUser(company);
		}
		List<DesignerDTO> dtos = designerService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/user/user_designerList";
	}
	
	@RequestMapping(value = "/designerDetail")
	public String designerDetail(Map<String, Object> map, Long id) {
		UserDTO user=getCurrentUserDTO();
		Integer type=user.getType();
		if(type==UserType.DecorateCompany.getValue()){//如果是装修公司
			CompanyDTO company=companyService.findCompanyByUserId(user.getId());
			map.put("companyId", company.getId());
			map.put("companyName", company.getName());
		}
		if (id != null) {
			DesignerDTO dto = designerService.load(id);
			map.put("n", dto);
			return "admin/user/user_designerDetail_edit";
		}
		map.put("provinces", provinceService.findAll());
		return "admin/user/user_designerDetail";
	}
	
	@RequestMapping(value = "/auditDesigner")
	public String auditDesigner(Map<String, Object> map, Long id) {
		if (id != null) {
			DesignerDTO dto = designerService.load(id);
			map.put("n", dto);
		}
		return "admin/user/user_designer_audit";
	}
	
	@RequestMapping(value = "/auditDesignerSave")
	@ResponseBody
	public String auditDesignerSave(DesignerDTO dto, JsonResultDTO resultDTO) {
		try {
			designerService.updateForAudit(dto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return okAndClose(resultDTO);
	}
	
	@Transactional
	@ResponseBody
	@RequestMapping("upload")
	public String upload(HttpServletRequest request) throws Exception {
		MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;  
        MultipartFile mf = mhs.getFile("file");
		Workbook book = WorkbookFactory.create(mf.getInputStream());

		Sheet sheet = book.getSheetAt(0);
		// 获取左上角的单元格
		int count = 1;
		Iterator<Row> iterable = sheet.rowIterator();
		iterable.next(); // 第一行是header，不要
		while (iterable.hasNext()) {
			Row row = iterable.next();
			UserDTO user = new UserDTO();
			row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
			String username = row.getCell(10).getStringCellValue();
			
			if (StringUtils.isBlank(username)) {
				continue;
			}
			user.setUsername(username);
			List<UserDTO> list = userService.find(user, null);
			if (CollectionUtils.isNotEmpty(list)) {
				continue;
			}
			
			String type = row.getCell(11).getStringCellValue().trim();
			if (StringUtils.isBlank(type)) {
				continue;
			}
			
			CompanyDTO company = new CompanyDTO();
			
			Role role = null;
			if ("V店".equalsIgnoreCase(type)) {
				user.setType(UserType.DecorateCompany.getValue());
				company.setRemark("V店");
				role = roleService.findByCode(RoleCode.Company);
			} else if (UserType.DecorateCompany.getRemark().equals(type)) {
				user.setType(UserType.DecorateCompany.getValue());
				role = roleService.findByCode(RoleCode.Company);
			} else if (UserType.City.getRemark().equals(type)) {
				user.setType(UserType.City.getValue());
				role = roleService.findByCode(RoleCode.City);
			} else if ("员工".equals(type)) {
				user.setType(UserType.Employee.getValue());
				role = roleService.findByCode(RoleCode.Employee);
			}
			
			company.setMobile(username);
			//公司名称
			String companyName = row.getCell(1).getStringCellValue().trim();
			company.setName(companyName);
			//营业执照
			String images = row.getCell(2).getStringCellValue().trim();
			company.setImages(images);
			//公司地址
			String address = row.getCell(3).getStringCellValue().trim();
			company.setOfficeAddress(address);
			company.setRegisterAddress(address);
			//开户银行
			String bank = row.getCell(4).getStringCellValue().trim();
			company.setBank(bank);
			//开户名称
			String accountName = row.getCell(5).getStringCellValue().trim();
			company.setAccountName(accountName);
			//开户账号
			String account = row.getCell(6).getStringCellValue().trim();
			company.setAccount(account);
			//纳税号
			String payAccount = row.getCell(7).getStringCellValue().trim();
			company.setPayAccount(payAccount);
			//发票抬头
			String invoice = row.getCell(8).getStringCellValue().trim();
			company.setInvoice(invoice);
			//姓名
			String name = row.getCell(9).getStringCellValue().trim();
			user.setRealName(name);
			user.setContactName(name);
			//折扣
			String discount = row.getCell(12).getStringCellValue().trim();
			company.setDiscount(discount);
			//状态
			String isUsed = row.getCell(13).getStringCellValue().trim();
			if ("启用".equals(isUsed)) {
				user.setDeleted(false);
			} else {
				user.setDeleted(true);
			}
			user.setPassword(passwordEncoder.encodePassword("123456", username));
			user.setMobile(username);
			long userId = userService.create(user);
			
			company.setName(name);
			
			
			User u = new User();
			u.setId(userId);
			company.setUser(u);
			if (user.getType() == UserType.DecorateCompany.getValue()) {
				companyService.create(company);
			}
			
			if (role != null) {
				UserRole userRole = new UserRole();
				userRole.setUserId(userId);
				userRole.setRoleId(role.getId());
				userRoleService.create(userRole);
			}
		}
		return okAndClose(new JsonResultDTO());
	}
	
	@RequestMapping(value = "/companyList")
	public String companyList(CompanyDTO dto, Map<String, Object> map, Page page) {
		List<CompanyDTO> dtos = companyService.find(dto, page);
		for (CompanyDTO c : dtos) {
			PayDTO pay = payService.findComanyPay(c.getUser().getId());
			c.setPay(pay);
			
			c.setProfit(profitService.findProfitByCompany(c.getId()));
		}
		map.put("list", dtos);
		map.put("query", dto);
		map.put("auditStatusList", AuditStatus.values());
		return "admin/user/user_companyList";
	}
	
	@RequestMapping(value = "/companyDetail")
	public String companyDetail(Map<String, Object> map, Long id) {
		if (id != null) {
			CompanyDTO dto = companyService.load(id);
			map.put("n", dto);
		}
		map.put("provinces", provinceService.findAll());
		return "admin/user/user_companyDetail";
	}
	
	@Transactional
	@RequestMapping(value = "/userCompanySave")
	@ResponseBody
	public String userCompanySave(CompanyDTO dto, JsonResultDTO resultDTO) {
		User user = (User) SpringSecurityUtils.getCurrentUser();
		if (dto.getId() == null) {
				UserDTO userDto = BeanMapper.map(dto.getUser(), UserDTO.class); 
				userDto.setPassword(passwordEncoder.encodePassword(userDto.getPassword(), userDto.getUsername()));
				userDto.setType(UserType.DecorateCompany.getValue());
				userDto.setQQ(dto.getUser().getQQ());
				userDto.setProvince(dto.getUser().getProvince());
				userDto.setCity(dto.getUser().getCity());
				userDto.setDistrict(dto.getUser().getDistrict());
				Long userId = userService.create(userDto);
				 
				userDto.setId(userId);
				dto.setUser(userDto);
				dto.setProvince(dto.getUser().getProvince());
				dto.setCity(dto.getUser().getCity());
				dto.setDistrict(dto.getUser().getDistrict());
				dto.setStatus(CompanyStatus.Audited.getValue());
				dto.setAuditTime(new Date());
				dto.setAuditUser(user);
				companyService.create(dto);
		} else {
			UserDTO oldUser = userService.load(dto.getUser().getId());
			oldUser.setProvince(dto.getUser().getProvince());
			oldUser.setCity(dto.getUser().getCity());
			oldUser.setDistrict(dto.getUser().getDistrict());
			oldUser.setContactName(dto.getUser().getContactName());
			oldUser.setMobile(dto.getUser().getMobile());
			oldUser.setSeq(dto.getUser().getSeq());
			oldUser.setQQ(dto.getUser().getQQ());
			userService.updateAllFields(oldUser);
			
			CompanyDTO oldCompany = companyService.load(dto.getId());
			oldCompany.setProvince(dto.getUser().getProvince());
			oldCompany.setCity(dto.getUser().getCity());
			oldCompany.setDistrict(dto.getUser().getDistrict());
			oldCompany.setName(dto.getName());
			oldCompany.setRegisterAddress(dto.getRegisterAddress());
			oldCompany.setOfficeAddress(dto.getOfficeAddress());
			oldCompany.setSalesType(dto.getSalesType());
			oldCompany.setWebSite(dto.getWebSite());
			oldCompany.setQuantity(dto.getQuantity());
			oldCompany.setIndustry(dto.getIndustry());
			oldCompany.setNature(dto.getNature());
			oldCompany.setRemark(dto.getRemark());
			oldCompany.setHeadImage(dto.getHeadImage());
			oldCompany.setDetails(dto.getDetails());
			companyService.updateAllFields(oldCompany);
		}
		return okAndClose(resultDTO);
	}
	
	@RequestMapping(value = "/profile")
	public String profileList(Map<String, Object> map, Page page) {
		UserDTO dto = new UserDTO();
		dto.setId(SpringSecurityUtils.getCurrentUser().getId());
		dto = userService.findOne(dto);
		map.put("provinces", provinceService.findAll());
		map.put("n", dto);
		if (dto.getType() == UserType.DecorateCompany.getValue()) {
			CompanyDTO companyDTO = new CompanyDTO();
			companyDTO.setUser(dto);
			companyDTO = companyService.findOne(companyDTO);
			map.put("c", companyDTO);
			map.put("company", UserType.DecorateCompany.getValue());
		}
		return "admin/user/user_profile";
	}
	
	@RequestMapping("setDepartment")
	public String setDepartment(Long id, Map<String, Object> map) throws Exception {
		map.put("departments", departmentService.findAll());
		map.put("user", userService.load(id));
		return "admin/user/user_setDepartment";
	}
	
	@ResponseBody
	@RequestMapping("saveDepartment")
	public String saveDepartment(Long id, Long departmentId, Double priceFactor) throws Exception {
		UserDTO user = userService.load(id);
		if (departmentId == null) {
			user.setDepartment(null);
		} else {
			user.setDepartment(new Department());
			user.getDepartment().setId(departmentId);
		}
		user.setPriceFactor(priceFactor);
		userService.updateAllFields(user);
		return ok();
	}
	
	@ResponseBody
	@RequestMapping("skins/default/laydate.css")
	public String laydatecss() throws Exception {
		return "";
	}
	@ResponseBody
	@RequestMapping("need/laydate.css")
	public String laydatecss2() throws Exception {
		return "";
	}
	
}
